﻿using System;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.ServiceModel.Activation;
using Autorent.DAL;

namespace Autorent.Service
{
    [ServiceContract(Namespace = "")]
    [AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
    public class AutorentMobileService
    {
        [OperationContract]
        public void AddDateReturn(DateTime dateReturn, int carId)
        {
            AutoRentEntities ctx = new AutoRentEntities();
            //update the autoOrder record for the selected car
            ctx.AutoOrders.FirstOrDefault(
                a => a.Auto_ID == carId && a.AutoOrderReturningDT == null).AutoOrderReturningDT = dateReturn;
            ctx.SaveChanges();
        }


        [OperationContract]
        public void AddCarDamage(string autoDamageDescription, int autoDamageCost, int carId)
        {
            AutoRentEntities ctx = new AutoRentEntities();
            //select order with maximum start date for selected car
            DateTime? dateStart = ctx.AutoOrders.Where(a => a.Auto_ID == carId).Max(a => a.AutoOrderRequestDT);
            //get the order for the selected car using car number and autoDamage params
            int? autoOrderId = (int)ctx.AutoOrders.FirstOrDefault(a => a.Auto_ID == carId && a.AutoOrderRequestDT == dateStart).AutoOrder_ID;
            AutoDamage damage = new AutoDamage()
            {
                AutoDamageDescription = autoDamageDescription,
                AutoDamageEstimatedCost = autoDamageCost,
                AutoOrder_ID = autoOrderId
            };
            ctx.AddToAutoDamages(damage);
            ctx.SaveChanges();
        }


        [OperationContract]
        public string GetCarNameById(int carId)
        {
            AutoRentEntities ctx = new AutoRentEntities();
            return ctx.Autoes.FirstOrDefault(a => a.Auto_ID == carId).AutoModel.ToString();
        }


        [OperationContract]
        public void AddGasQuantity(int gasQuantity, int carId)
        {
            AutoRentEntities ctx = new AutoRentEntities();
            ctx.Autoes.FirstOrDefault(a => a.Auto_ID == carId).AutoPetrolTankFilled = gasQuantity;
            ctx.SaveChanges();
        }
    }
}
